<!--
 * @Author: XieQiu 雪球
 * @Date: 2021-05-10 15:07:49
 * @LastEditTime: 2022-05-30 15:59:16
 * @LastEditors: 血雪球 wash0226@outlook.com
 * @Description: 巡检点管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="78"
        :has-qr="true"
        :qr-active="qrActive"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
      <!-- @qrShow="qrShow" -->
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName==='1'">收起筛选</p>
              <p v-if="activeName===''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">巡检点</div>
            <el-input v-model="pointName" placeholder="请输入巡检点名称" clearable @input="search" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="pointName" label="巡检点名称" />
        <el-table-column prop="errorRange" label="允许误差范围值(米)" />
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.pointId" slot-scope="scope">
            <!-- v-if="judgePermission(79, 'edit')" -->
            <!--  -->
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="qrShow(scope.row.pointCode)"
              :disabled="!scope.row.pointCode"
            >二维码</el-button>
            <!-- -->
            <!--  -->
            <el-button
              class="text-btn-cursor"
              type="text"
              v-if="judgePermission(79, 'edit')"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              v-if="judgePermission(79, 'delete')"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '巡查点位信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="巡查点名称 :" prop="pointName" class="w50p">
            <el-select
              v-model="formData.pointName"
              filterable
              allow-create
              default-first-option
              clearable
            >
              <el-option
                v-for="item in fishPondArr"
                :key="item.fishPondId"
                :label="item.pondName"
                :value="item.pondName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="巡查点编号:" prop="pointCode" class="w50p">
            <el-input v-model="formData.pointCode" placeholder="巡查点编号" clearable />
          </el-form-item>
          <el-form-item label="允许误差范围(米) :" prop="errorRange" class="w50p">
            <el-input v-model="formData.errorRange" placeholder="请输入误差范围值(米)" clearable />
          </el-form-item>
          <el-form-item class="w50p" label="经度 :" prop="longitude">
            <el-tooltip
              placement="top"
              effect="light"
              trigger="hover"
              content="请在下面的地图选择位置或者输入经纬度！"
            >
              <el-input v-model="formData.longitude" style="width:100%" />
            </el-tooltip>
          </el-form-item>
          <el-form-item class="w50p" label="纬度 :" prop="latitude">
            <el-tooltip
              placement="top"
              effect="light"
              trigger="hover"
              content="请在下面的地图或者选择位置输入经纬度！"
            >
              <el-input v-model="formData.latitude" style="width:100%" />
            </el-tooltip>
          </el-form-item>
        </el-form>
        <baidu-map
          class="map"
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          map-type="BMAP_HYBRID_MAP"
          @click="setCenterPoint"
        >
          <bm-marker
            :position="{ lng: center.lng, lat: center.lat }"
            :dragging="true"
            animation="BMAP_ANIMATION_BOUNCE"
          />
          <bm-control>
            <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
              <el-input
                v-model="keyword"
                type="text"
                placeholder="请输入地名关键字"
                style="background-color:#003947;"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </bm-auto-complete>
          </bm-control>
          <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
        </baidu-map>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>

      <el-dialog class="dialog" :visible.sync="qrCodeShow" width="20%" center>
        <div class="qrCode">
          <vue-qr
            :text="qrText"
            :margin="0"
            color-dark="#000"
            color-light="#fff"
            :logo-scale="0.15"
            :dot-scale="1"
            :size="200"
          />
        </div>
      </el-dialog>
      <!-- <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="facilityVOList"
        @closeDialog="isShowEquip = false"
      />-->
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import patrolApi from "@/api/pond-patrol-management/patrol-point-manage";
import fishPondApi from "@/api/basic-info-manage/fishPond";
import vueQr from "vue-qr";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
// import SeeEquip from "@/components/seeEquip/index.vue";
export default {
  name: "PatrolPoineManage",
  components: {
    ActionBar,
    Pagination,
    vueQr,
    BaseMainSlot
    // SearchBox
    // SeeEquip
  },
  mixins: [mymixin],
  data() {
    var validateInspectionPointCode = (rule, value, callback) => {
      setTimeout(() => {
        if (!value) {
          callback(new Error("编号不能为空！！！"));
        } else {
          var patrn = /[`~!@#$%^&*()\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）={}|《》？：“”【】、；‘'，。、]/im;
          if (patrn.test(value)) {
            callback(new Error("编号不能包含 $、&、￥等特殊字符"));
            // 如果包含特殊字符返回false
          } else {
            callback();
          }
        }
      }, 20);
    };
    return {
      obj: {
        name: ""
      },
      qrActive: false,
      qrCodeShow: false,
      qrText: "",
      logoImg: require("@/assets/logo.png"),
      // 巡检点名称
      pointName: "",
      // 是否能输入
      canInput: false,
      // 选中的数据项数组 ID组成
      inspectionPointIdList: [],
      // 地图相关值
      // center: { lng: 120.065772, lat: 30.89475 },
      center: { lng: 120.230648, lat: 30.811543 },
      // zoom: 15,
      zoom: 22,
      keyword: "",
      fishPondArr: [],
      nowfishPondId: "",
      facilityList: [],
      rules: {
        pointName: [
          { required: true, message: "请输入巡查点名称", trigger: "blur" }
        ],
        errorRange: [
          { required: true, message: "请输入误差范围值(米)", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "请在下方选择巡查点", trigger: "blur" }
        ],
        inspectionPointCode: [
          { validator: validateInspectionPointCode, trigger: "blur" }
        ],
        latitude: [
          {
            required: true,
            message: "请在下方选择巡查点或者输入经纬度",
            trigger: "change"
          }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false,
      facilityVOList: [],
      isShowEquip: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    // 动态添加数据
    formData: {
      deep: true,
      handler(val) {
        if (val.latitude || val.longitude) {
          this.center = {
            lng: val.longitude,
            lat: val.latitude
          };
        }
      }
    }
  },
  created() {
    // 获取表格数据
    this.searchData();
  },
  mounted() {
    this.search();
  },
  methods: {
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          pointName: this.pointName || undefined
        }
      };
      patrolApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
        }

        // 赋值数组
        this.tableData = [];
        if (data !== undefined) this.tableData = data.content;
        // console.log(this.tableData)
        this.addblankmet();
        this.resetActionBar();
      });
    },
    async searchData() {
      let params = {
        // facilityStatus: false
      };
      const { data: resp } = await fishPondApi.queryByCondition(params);
      this.fishPondArr = resp;
    },
    // 添加鱼塘
    addfacility() {
      // 新增点的对象数据数组
      let arr = this.fishPondArr.filter(item => {
        if (
          item.fishPondId !== undefined &&
          item.fishPondId === this.nowfishPondId
        ) {
          return item;
        } else {
          return false;
        }
      });
      // 判断是否存在该巡查点 facilityGroupId组成新数组
      let idList = this.facilityList.map(item => item.fishPondId);
      if (idList.includes(arr[0].fishPondId)) {
        this.$message.error("该鱼塘已经存在~");
        return;
      } else {
        this.facilityList = this.facilityList.concat(arr);
      }
      // }
    },
    changenowfacilityNo(val) {
      this.nowfishPondId = val;
      // console.log(val);
    },
    // 删除鱼塘
    removeFacilityTag(pointId) {
      this.facilityList.forEach((item, index) => {
        if (item.fishPondId === pointId) {
          this.facilityList.splice(index, 1);
        }
      });
    },
    setCenterPoint({ type, target, point, pixel, overlay }) {
      this.center.lng = point.lng;
      this.center.lat = point.lat;
      this.formData.latitude = point.lat;
      this.formData.longitude = point.lng;
    },
    seeEquip(row) {
      // console.log("a");
      this.facilityVOList = row.facilityVOList;
      this.isShowEquip = true;
      // console.log(this.isShowEquip);
      // console.log(row.facilityVOList);
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      this.facilityList = [];
      this.nowfishPondId = "";
      if (row.pointId) {
        this.formData = JSON.parse(JSON.stringify(row));
        if (this.formData.facilityVOList) {
          this.facilityList = this.formData.facilityVOList;
        }
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
        this.canInput = false;
        this.qrActive = true;
        this.center.lat = this.formData.latitude;
        this.center.lng = this.formData.longitude;
      } else {
        this.formData = {};
        this.qrActive = false;
      }
    },
    handleSelectionChange(list) {
      this.inspectionPointIdList = [];
      this.inspectionPointIdList = list.map(item => item.pointId);
      if (this.inspectionPointIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage(formData) {
      patrolApi.delList(this.inspectionPointIdList).then(res => {
        if (res.success) {
          this.search();
          this.$message.success(res.message);
          this.$refs[formData].resetFields();
          this.facilityList = [];
          this.nowfishPondId = "";
        } else {
          this.$message.warning(res.message || "删除失败");
        }
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          patrolApi.delList([row.pointId]).then(res => {
            if (res.success) {
              this.search();
              this.$message.success(res.message);
              this.facilityList = [];
              this.nowfishPondId = "";
            } else {
              this.$message.warning(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            patrolApi.edit(this.formData).then(res => {
              if (res.success) {
                this.search();
                this.$message.success(res.message || "修改成功！");
                this.facilityList = [];
                this.nowfishPondId = "";
              } else {
                this.$message.error(res.message || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            patrolApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success(res.message || "新增成功！");
                this.closeDialog();
                this.search();
                this.$refs[formData].resetFields();
                this.facilityList = [];
                this.nowfishPondId = "";
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    // 取消
    cancel(formData) {
      this.nowChanceStau = "";
      this.formData = {};
      this.facilityList = [];
      this.nowfishPondId = "";
      this.canInput = false;
      this.addActive = true;
      this.delActive = false;
      this.saveActive = false;
      this.cancelActive = false;
      this.editActive = false;
      this.center = { lng: 120.230648, lat: 30.811543 };
      this.dialogFormVisible = false;
      if (formData) {
        this.$refs[formData].resetFields();
      }
    },
    // 二维码
    qrShow(e) {
      // 将Number转为String
      // this.formData.organizationNo = this.formData.organizationNo.toString();
      // let fishPondId = this.formData.inspectionPointCode;
      // if (!fishPondId) {
      //   this.$message.warning("请先选择巡查点！！！");
      //   return;
      // }
      let newqrdata = {
        url: `${this.$baseurl.webUrl}mateFarmTraceSource/#/pages/facility-messages/facility-message?fishPondId=${e}`
        // pointId: this.formData.pointId
      };
      this.qrText = newqrdata.url;
      setTimeout(() => {
        this.qrCodeShow = true;
      }, 200);
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-form-item__label {
  min-width: 155px !important;
}

::v-deep .content {
  .table-box {
    width: 50% !important;
  }

  .form {
    width: 48% !important;
    position: relative;
    overflow: hidden;
  }
}
::v-deep .lng {
  .el-form-item__content {
    > span {
      width: 100%;
    }
  }

  .el-input__inner {
    min-width: 90px;
  }
}

::v-deep .lat {
  .el-form-item__content {
    > span {
      width: 100%;
    }
  }

  .el-form-item__label {
    text-align: end;
    min-width: 100px !important;
  }
}

.qrCode {
  text-align: center;
}

.map {
  position: absolute;
  bottom: 0px;
  left: 0;
  width: 100%;
  height: 66%;
  touch-action: none;
}

.noClick {
  cursor: not-allowed;
}

.df {
  display: flex;
  align-items: center;
  width: 100%;

  // 多选
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}

.dfs {
  ::v-deep .el-form-item__content {
    display: flex;
    /*flex-direction: column;*/
    flex-wrap: wrap;
    flex-direction: row;
    height: 120px;
    overflow-y: hidden;
  }
}

.tags {
  width: 100%;
  height: 90px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;

  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;

    i {
      font-size: 14px;
    }
  }
}

::v-deep .el-dialog__wrapper {
  .el-dialog {
    height: 78vh;
    margin-top: 0vh !important;

    .el-dialog__body {
      overflow: hidden;
      position: relative;
      height: 84%;
    }
  }
}
::v-deep .dialog {
  .el-dialog__headerbtn {
    top: 0;
    right: 10px;
  }
  .el-dialog {
    margin-top: 10vh !important;
    min-width: 15%;
    width: 200px !important;
    height: auto !important;
  }
}
</style>
